/**
 * 路由拦截操作
 */
import store from '../store'
import { storage, jcore } from '../utils/tools'
import router, { mainRoutes, globalRoutes } from './index'
import { getUserInfoMock, getterMenusMock } from '../utils/apiList/user'
import { fnAddDynamicMenuRoutes, fnCurrentRouteType, parseAddMenuType } from './handel'
//每个路由都进行拦截
router.beforeEach(async (to, from, next) => {
    // 添加动态(菜单)路由
    // 1. 已经添加 or 全局路由, 直接访问
    // 2. 获取菜单列表, 添加并保存本地存储
    if (router.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
        next()
    } else {
        try {
            let params = jcore.getQueryObject()
            let token = params.token || storage.getCookie('token')
            if (!token) {
                throw params
            }
            console.log(token, '-->>> token')
            storage.setCookie("token", token); //存储token
            // 获取用户信息
            let res = await getUserInfoMock(token)
            if (!res || res == "no contnet") {
                throw res
            }
            // 存储用户信息第一个(默认第一个)
            let firstUserInfo = res.data[0]
            storage.setLocal('authorityList', firstUserInfo)
            await store.dispatch('app/setUserInfo', firstUserInfo)
            storage.setLocal('dutylist', res)

            // 获取动态路由
            let resRoute = await getterMenusMock(res)
            let activeRouteList = resRoute
            let menuList = parseAddMenuType(activeRouteList)
            // 动态注册路由
            let routes = fnAddDynamicMenuRoutes(menuList)
            mainRoutes.name = 'main-dynamic'
            mainRoutes.children = routes;
            router.addRoutes([
                mainRoutes,
                { path: '*', redirect: { name: '404' } }
            ])
            await store.dispatch('app/setMenuList', menuList)
            let firstRoute = storage.getSession('sidebarList') || menuList[0]
            router.isAddDynamicMenuRoutes = true

            storage.setSession('sidebarList', firstRoute)
            store.dispatch('app/setSidebarList', firstRoute)
            let [first] = firstRoute.children
            let code = storage.getSession('selectCode')
            if (code) {
                next({ ...to, replace: true })
            } else {
                next({ name: first.code, replace: true })
            }
        } catch (error) {
            console.log(error);
            console.log(`%c${error} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
            next({ path: '/login' })
        }

    }

})